/*
 * 版权所有 (c) 2022-2099 TBIT。保留所有权利
 */

/*
 * 版权所有 (c) 2022-2099 TBIT。保留所有权利
 */

package com.tbit.uqbike.push.filter.servlet;

import cn.hutool.core.util.StrUtil;
import com.tbit.common.utils.TraceUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;

/**
 * 分布式链路追踪 - traceId 过滤器
 *
 * <p>
 * 1、获取/生成traceId
 * </p>
 *
 * @author <a href="mailto:zhang.zhiliang@tbit.com.cn">Zhang ZhiLiang</a>
 * @version 1.0
 * @see <a href="http://adsl1.tbit.com.cn:21490/pages/viewpage.action?pageId=82182491">订单号规范</a>
 * @since 2024/5/13
 */
@Order(1)
@Slf4j
@Component
public class TraceFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        Filter.super.init(filterConfig);
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        try{
            String traceId = TraceUtil.getTraceIdByRequest((HttpServletRequest) servletRequest);
            if (StrUtil.isBlank(traceId)){
                traceId = TraceUtil.buildTraceId();
            }
            TraceUtil.setTraceId(traceId);
        }catch (Exception e){
            log.error("链路追踪traceId操作异常！",e);
        }
        filterChain.doFilter(servletRequest,servletResponse);
        // 执行完成后，进行线程traceId的清楚
        TraceUtil.cleanTraceId();
    }

    @Override
    public void destroy() {
        TraceUtil.cleanTraceId();
        Filter.super.destroy();
    }
}
